package com.conversationboard.controller;

import java.io.IOException;
import java.security.Principal;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.model.Search;
import com.conversationboard.model.SearchResult;
import com.conversationboard.model.User;
import com.conversationboard.model.enums.SearchType;
import com.conversationboard.site.Site;

@WebServlet(name = "SearchControllerServlet", urlPatterns = "/SearchControllerServlet")
public class SearchControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -3329910811994792890L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Site.incrementPageHitCount();

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			Principal principal = request.getUserPrincipal();
			String loginId = null;

			if (principal != null) {
				loginId = principal.getName();
			}

			User user = User.get(loginId);

			String searchType = request.getParameter("searchtype");
			String terms = request.getParameter("terms");
			int offset = Integer.parseInt(request.getParameter("offset"));

			/* If you've not entered anything, it's an error */

			if (terms.length() == 0) {
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/search-failed.jsp");
				dispatcher.forward(request, response);
				return;
			}

			SearchType type = SearchType.TITLE;

			if (searchType.equals("title")) {
				type = SearchType.TITLE;
			} else if (searchType.equals("displayname")) {
				type = SearchType.DISPLAYNAME;
			} else if (searchType.equals("combined")) {
				type = SearchType.COMBINED;
			}

			Search search = new Search();
			List<SearchResult> searchResults = search.search(terms, offset, type);

			offset += 15;
			request.setAttribute("terms", terms);
			request.setAttribute("user", user);
			request.setAttribute("searchresults", searchResults);
			request.setAttribute("searchtype", searchType);
			request.setAttribute("offset", (offset + ""));

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/searchresults.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
